/*
 *	基于JQ的js方法
*/
function setCookie( name, value, expiredays=7 ) {
  var exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
};
function getCookie( name ) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
  if (arr = document.cookie.match(reg))
    return (arr[2])
  else
    return null
};
function delCookie( name ) {
  var exp = new Date()
  exp.setTime(exp.getTime() - 1)
  var cval = null
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
  if( arr = document.cookie.match(reg) ){
    cval = (arr[2])
  }
  if (cval != null)
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
};
function onlyNum(val) {
  if (val.length == 1) {
    val = val.replace(/[^1-9]/g, '');
  } else {
    val = val.replace(/\D/g, '').replace(/^0+/g, '')
  }
  return val
};
function checkMobile(val) {
  var reg = /^1[3|4|5|7|8|9][0-9]{9}$/
  // var reg = /^1[0-9]{10}$/
  if( reg.test(val) ) {
    return true
  } else {
    return false
  }
};
function IdentityCodeValid(code) { 
  var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
  var tip = "";
  var pass= true;
  var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
  if( !code ){
      tip = "身份证号不能为空";
      pass = false;
  } else if( !regIdCard.test(code) ){
      tip = "请输入正确的身份证号码";
      pass = false;
  } else if(!city[code.substr(0,2)]){
      // tip = "地址编码错误";
      tip = "请输入正确的身份证号码";
      pass = false;
  } else {
      //18位身份证需要验证最后一位校验位
      if( code.length==18 ){
          code = code.toUpperCase();
          code = code.split('');
          var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
          var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
          var sum = 0;
          var ai = 0;
          var wi = 0;
          for( var i = 0; i<17; i++ ){
            ai = code[i];
            wi = factor[i];
            sum += ai * wi;
          }
          var last = parity[sum%11];
          if( parity[sum%11]!=code[17] ){
              // tip = "校验位错误";
              tip = "请输入正确的身份证号码";
              pass = false;
          }
      }
  }
  return { 'tips': tip, 'type': pass };
};
function specificTime(format, timestamp) {
  /**
    specificTime('Y-m-d','1350052653');       // => 2012-10-11 
    specificTime('Y-m-d H:i:s','1350052653'); // => 2012-10-12 22:37:33
  */
  var a, jsdate = ((timestamp) ? new Date(timestamp*1000) : new Date());
  var pad = function (n, c) {
    if ((n = n + "").length < c) {
      return new Array(++c - n.length).join("0") + n;
    } else {
      return n;
    }
  };
  var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var txt_ordin = { 1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st" };
  var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var f = {
    // Day
    d: function () { return pad(f.j(), 2) },
    D: function () { return f.l().substr(0, 3) },
    j: function () { return jsdate.getDate() },
    l: function () { return txt_weekdays[f.w()] },
    N: function () { return f.w() + 1 },
    S: function () { return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th' },
    w: function () { return jsdate.getDay() },
    z: function () { return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0 },
    // Week 
    W: function () {
      var a = f.z(), b = 364 + f.L() - a;
      var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
      if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
        return 1;
      } else {
        if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
          nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
          return date("W", Math.round(nd2.getTime() / 1000));
        } else {
          return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
        }
      }
    },
    // Month 
    F: function () { return txt_months[f.n()] },
    m: function () { return pad(f.n(), 2) },
    M: function () { return f.F().substr(0, 3) },
    n: function () { return jsdate.getMonth() + 1 },
    t: function () {
      var n;
      if ((n = jsdate.getMonth() + 1) == 2) {
        return 28 + f.L();
      } else {
        if (n & 1 && n < 8 || !(n & 1) && n > 7) {
          return 31;
        } else {
          return 30;
        }
      }
    },
    // Year 
    L: function () { var y = f.Y(); return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0 },
    //o not supported yet 
    Y: function () { return jsdate.getFullYear() },
    y: function () { return (jsdate.getFullYear() + "").slice(2) },
    // Time 
    a: function () { return jsdate.getHours() > 11 ? "pm" : "am" },
    A: function () { return f.a().toUpperCase() },
    B: function () {
      // peter paul koch: 
      var off = (jsdate.getTimezoneOffset() + 60) * 60;
      var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
      var beat = Math.floor(theSeconds / 86.4);
      if (beat > 1000) beat -= 1000;
      if (beat < 0) beat += 1000;
      if ((String(beat)).length == 1) beat = "00" + beat;
      if ((String(beat)).length == 2) beat = "0" + beat;
      return beat;
    },
    g: function () { return jsdate.getHours() % 12 || 12 },
    G: function () { return jsdate.getHours() },
    h: function () { return pad(f.g(), 2) },
    H: function () { return pad(jsdate.getHours(), 2) },
    i: function () { return pad(jsdate.getMinutes(), 2) },
    s: function () { return pad(jsdate.getSeconds(), 2) },
    O: function () {
      var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
      if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
      return t;
    },
    P: function () { var O = f.O(); return (O.substr(0, 3) + ":" + O.substr(3, 2)) },
    c: function () { return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P() },
    U: function () { return Math.round(jsdate.getTime() / 1000) }
  };
  return format.replace(/([\]?([a-zA-Z])/g, function (t, s) {
    var ret;
    if (t != s) {          // escaped
      ret = s;
    } else if (f[s]) {   // a date function exists
      ret = f[s]();
    } else {              // nothing special
      ret = s;
    }
    return ret;
  })
};
function floatNum( val, num=1 ) {
  if(val.length==1){
    val = val.replace(/[^\d]/g, '');
  } else {
    val = val.replace(/[^0-9.]*/g, '');               //清除“数字”和“.”以外的字符     
    val = val.replace(/\.{2,}/g, '.');              //只保留第一个. 清除多余的     
    val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    if (num == 1) {
      val = val.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3');    //只能输入一个小数
    } else if(num==2) {
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');   //只能输入两个小数   
    } else if(num==4) {
      val = val.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3');   //只能输入四位个小数   
    } else if(num==8) {
      val = val.replace(/^(\-)*(\d+)\.(\d\d\d\d\d\d\d\d).*$/, '$1$2.$3');   //只能输入四位个小数   
    }
    if( val.indexOf('.')<0 && val != '' ){ //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额    
      val = parseFloat(val);
    }
  }
  return val
};
function phoneType() {
  var browser = {
    versions: function () {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {  //移动终端浏览器版本信息
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile/i) || !!u.match(/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
      iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
      };
    } (),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
  }
  if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
    var phoneInfo = { type: 1, text: '这是苹果手机' }
    return phoneInfo
  } else if (browser.versions.android) {
    var phoneInfo = { type: 2, text: '这是安卓手机' }
    return phoneInfo
  } else {
    return false
  }
};
function backTop() {
  var timer = null
  clearInterval(timer)
  timer = setInterval(function(){
    var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
    var ispeed = Math.floor(-scrollTop/3);
    if( scrollTop==0 ){ clearInterval(timer); }
    document.documentElement.scrollTop=document.body.scrollTop=scrollTop+ispeed;
  }, 10)
};
function getMore(fn) {
  window.addEventListener('scroll', ()=>{
    var docHeight = document.body.clientHeight - window.screen.height
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    if( scrollTop>=(docHeight-300) ){
      fn()
    }
  })
};
function upload_Oss(btn) {
  var host = ''
  var policy = ''
  var dir = ''
  var expire = 0
  var accessid = ''
  var signature = ''
  var file_name = ''
  var dl_len = 0;
  var imgAll = []
  var pathArr = []
  var success_len = 0;
  var uploader = new plupload.Uploader({
    multi_selection: false, //是否可以在文件浏览对话框中选择多个文件，true为可以，false为不可以 
    browse_button: btn, //触发文件选择对话框的按钮，为那个元素id
    url: 'http://oss.aliyuncs.com', //服务器端的上传页面地址
    flash_swf_url: '../lib/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
    silverlight_xap_url: '../lib/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
    filters: {
      mime_types: [ //只允许上传图片
        { title: "Image files", extensions: "jpg,gif,png" }
      ],
      max_file_size: '5000kb', // 上传文件的最大容量
      prevent_duplicates: false // 不允许选取重复文件
    },
    init: {
      'PostInit': function (up) {//init初始化执行后的回调
        set_upload_param(up)
      },
      'BeforeUpload': function (up, file) {//文件开始上传之前的回调
        set_upload_param(up, file.name)
      },
      'FilesAdded': function (uploader, files) {//当文件添加到上传队列后触发
        dl_len = files.length;
        uploader.is_addFile && uploader.is_addFile(files.length);
        files.forEach(function (item, i) {
          previewImage(item, function (imgsrc) {
            imgAll.push(imgsrc)
          })
        });
      },
      'FilesRemoved': function (uploader, files) {//当文件从上传队列移除后触发

      },
      'FileUploaded': function (uploader, file, response) {//文件上传成功的回调
        if (response.status == 200) {
          success_len++;
          pathArr.push(host + '/' + dir + file_name)
          if (success_len == dl_len) {
            uploader.fn && uploader.fn(pathArr);
            console.log(success_len)
            success_len = 0;
          }
        }
      },
      'Error': function (uploader, err) { //发生错误的回调
        console.log(err)
        if( err.code=='-600' ){
          layer.msg('图片不能大于5000kb', {icon: 2})
        }
      }
    },
  });
  uploader.init();

  //获取签名请求
  function send_request(url) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp != null) {
      xmlhttp.open("GET", url, false);
      xmlhttp.send(null);
      return JSON.parse(xmlhttp.responseText)
    } else {
      alert("Your browser does not support XMLHTTP.");
    }
  };

  //var signature_state = get_signature(expire);
  //验证签名是否失效，如果失效重新获取
  function get_signature(expire) {
    var now = Date.parse(new Date()) / 1000;
     var nowHost = window.location.protocol+'//'+window.location.host;
    // var nowHost = 'https://sj1.51tuanli.com';
    if (expire < now + 3) {//3 为0.3s的缓冲时间
      var data = send_request(nowHost+'/api/get_oss_info')
      host = data.host;
      policy = data.policy;
      dir = data.dir;
      expire = data.expire;
      accessid = data.accessid;
      signature = data.signature;
      return true;
    }
    return false;
  };

  //随机文件名字
  function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  //获取图片后缀
  function get_suffix(filename) {
    var pos = filename.lastIndexOf('.')
    var suffix = ''
    if (pos != -1) {
      suffix = filename.substring(pos)
    }
    return suffix;
  }

  //动态配置上传参数
  function set_upload_param(up, filename) {
    var suffix = '';
    //验证签名
    get_signature(expire);
    //是否随机文件名
    if (filename != '' && filename) {
      console.log(filename)
      suffix = get_suffix(filename)
      file_name = random_string(10) + suffix;
    } else {
      file_name = '${filename}';
    }
    var new_multipart_params = {
      'Filename': dir + file_name,
      'key': dir + file_name,//'${filename}'
      'policy': policy,
      'OSSAccessKeyId': accessid,
      'success_action_status': '200', //让服务端返回200,不然，默认会返回204
      'signature': signature,
    };
    up.setOption({
      'url': host,
      'multipart_params': new_multipart_params
    });
  }

  //删除单个待上传图片
  function removeFile(up, file, self) {
    up.removeFile(file);
    self.parentNode.parentNode.removeChild(self.parentNode);
    uploader.is_addFile && uploader.is_addFile(up.files.length, self.index);
  }

  //生成缩略图方法
  function previewImage(file, callback) {
    if (!file || !/image\//.test(file.type)) return; //确保文件是图片
    if (file.type == 'image/gif') {//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
      var fr = new mOxie.FileReader();
      fr.onload = function () {
        callback(fr.result);
        fr.destroy();
        fr = null;
      }
      fr.readAsDataURL(file.getSource());
    } else {
      var preloader = new mOxie.Image();
      preloader.onload = function () {
        preloader.downsize(300, 300);//先压缩一下要预览的图片,宽300，高300
        var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
        callback && callback(imgsrc); //callback传入的参数为预览图片的url
        preloader.destroy();
        preloader = null;
      };
      preloader.load(file.getSource());
    }
  }
  // return uploader;
  return { 'events': uploader, 'val': imgAll };
}

//数据模型 time0 open1 close2 min3 max4 vol5 tag6 macd7 dif8 dea9
//['2015-10-19',18.56,18.25,18.19,18.56,55.00,0,-0.00,0.08,0.09] 
//数组处理
function splitData(rawData) {
  var datas = [];
  var times = [];
  var vols = [];
  var macds = []; var difs = []; var deas = [];
  for (var i = 0; i < rawData.length; i++) {
      datas.push(rawData[i]);
      times.push(rawData[i].splice(0, 1)[0]);
      vols.push(rawData[i][4]);
      macds.push(rawData[i][6]);
      difs.push(rawData[i][7]);
      deas.push(rawData[i][8]);
  }
  return {
      datas: datas,
      times: times,
      vols: vols,
      macds: macds,
      difs: difs,
      deas: deas
  };
}

//MA计算公式
function calculateMA(dayCount, data) {
  console.log(data)
  var result = [];
  for (var i = 0, len = data.times.length; i < len; i++) {
      if (i < dayCount) {
          result.push('-');
          continue;
      }
      var sum = 0;
      for (var j = 0; j < dayCount; j++) {
          sum += parseFloat( data.datas[i - j][1] );
      }
      result.push((sum / dayCount).toFixed(2));
  }
  return result;
}
    
// K线图主要函数
function market_chart(obj, $data){    
    var rawData = splitData($data);
    var option = {
      backgroundColor: '#131E30',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      legend: {
        data: ['MA5', 'MA10', 'MA20', 'MA30'],
      },
      grid: [{
        top: '10%',
        left: '12%',
        right: '2%',
        height: '55%'
      },{
        top: '72%',
        left: '12%',
        right: '2%',
        height: '10%'
      },{
        top: '85.5%',
        left: '12%',
        right: '2%',
        height: '14%'
      }],
      xAxis: [{
        type: 'category',
        data: rawData.times,
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        splitNumber: 20,
        min: 'dataMin',
        max: 'dataMax'
      },{
        type: 'category',
        gridIndex: 1,
        data: rawData.times,
        axisLabel: {show: false}
      },{
        type: 'category',
        gridIndex: 2,
        data: rawData.times,
        axisLabel: {show: false}
      }],
      yAxis: [{
        scale: true,
        splitArea: {
          show: false
        }
      },{
        gridIndex: 1,
        splitNumber: 3,
        axisLine: {onZero: false},
        axisTick: {show: false},
        splitLine: {show: false},
        axisLabel: {show: true}
      },{
        gridIndex: 2,
        splitNumber: 4,
        axisLine: {onZero: false},
        axisTick: {show: false},
        splitLine: {show: false},
        axisLabel: {show: true}
      }],
      dataZoom: [{
        type: 'inside',
        xAxisIndex: [0, 0],
        start:  1,
        end: 100
      },{
        show: false,
        xAxisIndex: [0, 1],
        type: 'slider',
        top: '97%',
        start: 1,
        end: 100
      },{
        show: false,
        xAxisIndex: [0, 2],
        type: 'slider',
        start: 1,
        end: 100
      }],
      series: [{
          name: 'K线周期图表',
          type: 'candlestick',
          data: rawData.datas,
          itemStyle: {
            normal: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          },
        }, {
          name: 'MA5',
          type: 'line',
          data: calculateMA(5, rawData),
          smooth: true,
          lineStyle: {
            normal: {
              opacity: 0.8
            }
          }
        }, {
          name: 'MA10',
          type: 'line',
          data: calculateMA(10, rawData),
          smooth: true,
          lineStyle: {
            normal: {
              opacity: 0.8
            }
          }
        },  {
          name: 'MA20',
          type: 'line',
          data: calculateMA(20, rawData),
          smooth: true,
          lineStyle: {
            normal: {
              opacity: 0.8
            }
          }
        },  {
          name: 'MA30',
          type: 'line',
          data: calculateMA(30, rawData),
          smooth: true,
          lineStyle: {
            normal: {
              opacity: 0.8
            }
          }
        }, {
          name: 'Volumn',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: rawData.vols,
          itemStyle: {
            normal: {
              color: function(params) {
                var colorList;
                if (rawData.datas[params.dataIndex][1]>rawData.datas[params.dataIndex][0]) {
                  colorList = '#ef232a';
                } else {
                  colorList = '#14b143';
                }
                return colorList;
              },
            }
          }
        },{
          name: 'MACD',
          type: 'bar',
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: rawData.macds,
          itemStyle: {
            normal: {
              color: function(params) {
                var colorList;
                if (params.rawData >= 0) {
                  colorList = '#ef232a';
                } else {
                  colorList = '#14b143';
                }
                return colorList;
              },
            }
          }
        },{
            name: 'DIF',
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: rawData.difs
        },{
            name: 'DEA',
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: rawData.deas
        }
      ]
    };
    var myChart = echarts.init(document.getElementById(obj));
    myChart.setOption(option, true);
}